using System.Text.Json;
using LicenseApp.Client;

namespace LicenseApp.Test;

/// <summary>
/// 使用天数调试工具
/// </summary>
public static class UsageDebugger
{
    /// <summary>
    /// 分析当前的使用天数计算问题
    /// </summary>
    public static void AnalyzeUsageDays()
    {
        Console.WriteLine("=== 使用天数调试分析 ===");
        Console.WriteLine();

        try
        {
            // 获取当前授权信息
            var licenseInfo = LicenseManager.GetLicenseInfo();
            if (licenseInfo == null)
            {
                Console.WriteLine("❌ 未找到授权信息");
                return;
            }

            Console.WriteLine("1. 授权信息:");
            Console.WriteLine($"   生效日期: {licenseInfo.StartDate:yyyy-MM-dd}");
            Console.WriteLine($"   授权天数: {licenseInfo.Days}");
            Console.WriteLine($"   到期日期: {licenseInfo.EndDate:yyyy-MM-dd}");
            Console.WriteLine();

            // 分析使用记录文件
            AnalyzeUsageFiles(licenseInfo);

            // 计算正确的使用天数
            CalculateCorrectUsageDays(licenseInfo);

        }
        catch (Exception ex)
        {
            Console.WriteLine($"❌ 分析过程中发生错误: {ex.Message}");
        }

        Console.WriteLine();
        Console.WriteLine("=== 分析完成 ===");
    }

    private static void AnalyzeUsageFiles(LicenseInfo licenseInfo)
    {
        Console.WriteLine("2. 使用记录文件分析:");

        // 获取应用程序路径
        string assemblyFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
        string assemblyDirPath = System.IO.Path.GetDirectoryName(assemblyFilePath) ?? "";

        // 检查各种可能的使用记录文件
        var possibleFiles = new[]
        {
            System.IO.Path.Combine(assemblyDirPath, "usage.dat"),
            System.IO.Path.Combine(assemblyDirPath, "usage_backup.dat"),
            System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "LicenseApp", "usage.dat"),
            System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "LicenseApp", "usage.dat")
        };

        foreach (var filePath in possibleFiles)
        {
            if (System.IO.File.Exists(filePath))
            {
                Console.WriteLine($"   ✅ 找到文件: {filePath}");
                AnalyzeUsageFile(filePath, licenseInfo);
            }
            else
            {
                Console.WriteLine($"   ❌ 文件不存在: {filePath}");
            }
        }
    }

    private static void AnalyzeUsageFile(string filePath, LicenseInfo licenseInfo)
    {
        try
        {
            var content = System.IO.File.ReadAllText(filePath);
            Console.WriteLine($"      文件内容长度: {content.Length} 字符");

            // 尝试解析JSON
            var usageRecord = JsonSerializer.Deserialize<UsageRecord>(content);
            if (usageRecord != null)
            {
                Console.WriteLine($"      记录的使用天数: {usageRecord.UsedDays}");
                Console.WriteLine($"      首次使用日期: {usageRecord.FirstUsedDate:yyyy-MM-dd}");
                Console.WriteLine($"      最后使用日期: {usageRecord.LastUsedDate:yyyy-MM-dd}");
                Console.WriteLine($"      使用日期记录数: {usageRecord.UsageDates?.Count ?? 0}");

                if (usageRecord.UsageDates?.Count > 0)
                {
                    var earliestDate = usageRecord.UsageDates.Min();
                    var latestDate = usageRecord.UsageDates.Max();
                    Console.WriteLine($"      最早使用日期: {earliestDate:yyyy-MM-dd}");
                    Console.WriteLine($"      最晚使用日期: {latestDate:yyyy-MM-dd}");

                    // 检查是否有异常的日期
                    if (earliestDate < licenseInfo.StartDate.Date)
                    {
                        Console.WriteLine($"      ⚠️  警告: 最早使用日期 {earliestDate:yyyy-MM-dd} 早于授权生效日期 {licenseInfo.StartDate:yyyy-MM-dd}");
                    }
                }

                // 验证使用天数计算
                var today = DateTime.Now.Date;
                var expectedDays = Math.Max(1, (int)(today - licenseInfo.StartDate.Date).TotalDays + 1);
                if (usageRecord.UsedDays != expectedDays)
                {
                    Console.WriteLine($"      ⚠️  使用天数不匹配:");
                    Console.WriteLine($"         记录值: {usageRecord.UsedDays}");
                    Console.WriteLine($"         期望值: {expectedDays}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"      ❌ 解析文件失败: {ex.Message}");
        }
    }

    private static void CalculateCorrectUsageDays(LicenseInfo licenseInfo)
    {
        Console.WriteLine("3. 正确的使用天数计算:");

        var today = DateTime.Now.Date;
        var startDate = licenseInfo.StartDate.Date;

        Console.WriteLine($"   当前日期: {today:yyyy-MM-dd}");
        Console.WriteLine($"   生效日期: {startDate:yyyy-MM-dd}");

        if (today < startDate)
        {
            Console.WriteLine($"   ✅ 当前日期早于生效日期，使用天数应为: 0");
        }
        else
        {
            var correctUsedDays = (int)(today - startDate).TotalDays + 1;
            var remainingDays = licenseInfo.Days - correctUsedDays;

            Console.WriteLine($"   ✅ 正确的使用天数应为: {correctUsedDays}");
            Console.WriteLine($"   ✅ 剩余天数应为: {remainingDays}");
            Console.WriteLine($"   ✅ 到期日期: {licenseInfo.EndDate:yyyy-MM-dd}");

            if (correctUsedDays > licenseInfo.Days)
            {
                Console.WriteLine($"   ⚠️  授权已过期 {correctUsedDays - licenseInfo.Days} 天");
            }
        }
    }

    /// <summary>
    /// 清理异常的使用记录
    /// </summary>
    public static void CleanupUsageRecords()
    {
        Console.WriteLine("=== 清理使用记录 ===");
        Console.WriteLine();

        var result = Console.ReadLine();
        if (result?.ToLower() != "yes")
        {
            Console.WriteLine("操作已取消");
            return;
        }

        try
        {
            // 获取应用程序路径
            string assemblyFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName ?? "";
            string assemblyDirPath = System.IO.Path.GetDirectoryName(assemblyFilePath) ?? "";

            var filesToDelete = new[]
            {
                System.IO.Path.Combine(assemblyDirPath, "usage.dat"),
                System.IO.Path.Combine(assemblyDirPath, "usage_backup.dat")
            };

            foreach (var file in filesToDelete)
            {
                if (System.IO.File.Exists(file))
                {
                    System.IO.File.Delete(file);
                    Console.WriteLine($"✅ 已删除: {file}");
                }
            }

            Console.WriteLine();
            Console.WriteLine("✅ 使用记录清理完成，下次启动时将重新计算");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"❌ 清理失败: {ex.Message}");
        }
    }

    // 内部类，用于反序列化使用记录
    private class UsageRecord
    {
        public int UsedDays { get; set; }
        public DateTime LastUsedDate { get; set; }
        public DateTime FirstUsedDate { get; set; }
        public List<DateTime>? UsageDates { get; set; }
    }
}
